<?php
/**
 * cookie操作类
 * User: 4399-0661
 * Date: 15-5-29
 * Time: 下午3:38
 */

namespace Library\tools;


class LibCookie extends \LibBase
{
    /**
     * 设置cookie
     * @param $name
     * @param $value
     * @param bool $encode
     * @param int $expire
     * @param null $path
     * @param null $domain
     * @param bool $secure
     * @param bool $httponly
     * @return bool
     */
    public function set($name, $value, $encode = false, $expire = 0, $path = null, $domain = null, $secure = false, $httponly = false)
    {
        $encode && $value && $value = base64_encode(serialize($value));
        $path = $path ? $path : '/';
        return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
    }

    /**
     * 获取cookie
     * @param $name
     * @param bool $decode
     * @return bool|mixed
     */
    public function get($name, $decode = false)
    {
        if ($this->exists($name)) {
            $value = $_COOKIE[$name];
            $value && $decode && $value = unserialize(base64_decode($value));
            return $value;
        }
        return false;
    }

    /**
     * 删除单个cookie
     * @param $name
     * @return bool
     */
    public function delete($name)
    {
        if ($this->exists($name)) {
            self::set($name, '', false, -3600);
            unset($_COOKIE[$name]);
        }
        return true;
    }

    /**
     * 清空cookie
     * @return bool
     */
    public function deleteAll()
    {
        foreach ($_COOKIE as $key => $value) {
            $this->delete($key);
        }
        return true;
    }

    /**
     * 判断某个cookie是否存在
     * @param $name
     * @return bool
     */
    public function exists($name)
    {
        return isset($_COOKIE[$name]);
    }
} 